<template>
  <div class="content-box card">
    <div class="categorize-container">
      <div class="top-box">
        <el-segmented v-model="value" :options="options" size="default" @change="loadCareMissionCategorizeList" />
        <div style="position: relative; bottom: 1px; left: 12px; display: inline-block" v-auth="'mission_index_save'">
          <el-button
            :icon="Plus"
            style="height: 29px; line-height: 29px"
            type="primary"
            plain
            size="default"
            @click="addCategorize"
          >
            添加任务分类
          </el-button>
          <el-button
            :icon="Plus"
            style="height: 29px; line-height: 29px"
            type="primary"
            plain
            size="default"
            @click="openDrawer('添加', 0)"
          >
            添加照护项目
          </el-button>
        </div>
      </div>
      <div class="categorize-box" v-for="mc in careMissionCategorizeList" :key="mc.id">
        <div class="categorize-title">
          <el-badge v-if="value === '查看自建任务'" :offset="[15, 5]" :value="'排序：' + mc.sort" class="item">
            <span>{{ mc.companyId == 1 ? "平台分类" : "自建分类" }}： {{ mc.name }}</span>
          </el-badge>
          <span v-else>{{ mc.companyId == 1 ? "平台分类" : "自建分类" }}： {{ mc.name }}</span>
          <div style="display: inline-block; float: right" v-if="value === '查看自建任务'">
            <el-button
              type="primary"
              :icon="Plus"
              size="default"
              style="position: relative; bottom: 2px"
              @click="openDrawer('添加', mc.id)"
              v-auth="'mission_index_save'"
              plain
            >
              添加照护项目
            </el-button>
            <el-button
              type="primary"
              :icon="Edit"
              size="default"
              style="position: relative; bottom: 2px"
              @click="editCategorizeName(mc)"
              v-auth="'mission_index_save'"
              plain
            >
              编辑分类名称
            </el-button>
            <el-button
              type="primary"
              :icon="Sort"
              size="default"
              style="position: relative; bottom: 2px"
              @click="setCategorizeSort(mc)"
              v-auth="'mission_index_save'"
              plain
            >
              设置分类排序
            </el-button>
            <el-button
              type="danger"
              :icon="Delete"
              size="default"
              style="position: relative; bottom: 2px"
              @click="deleteCategorize(mc)"
              v-auth="'mission_index_delete'"
              plain
            >
              删除分类
            </el-button>
          </div>
        </div>
        <div class="categorize-content" style="width: 100%">
          <el-table border :data="mc.careMissions" style="width: 100%">
            <el-table-column prop="companyId" label="任务来源" width="100" align="center">
              <template #default="scope">
                <span v-if="scope.row.companyId == 1">
                  <el-tag type="success" effect="dark" size="small">平台推荐</el-tag>
                </span>
                <span v-else>
                  <el-tag type="primary" effect="dark" size="small">自建任务</el-tag>
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="任务名称" width="180">
              <template #default="scope">
                <span style="font-weight: 500">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="" label="建议实施时段" width="200" align="left">
              <template #default="scope">
                <div v-if="scope.row.isDailyMission">
                  每日：
                  <span v-if="scope.row.dailyMissionStartTime && scope.row.dailyMissionEndTime">
                    {{ scope.row.dailyMissionStartTime }} - {{ scope.row.dailyMissionEndTime }}
                  </span>
                  <span v-else> 不限制时间段 </span>
                </div>

                <span v-else> 根据需求及老人情况 </span>
              </template>
            </el-table-column>
            <el-table-column prop="dailyMissionExecutionCount" label="建议执行次数" width="180" align="left">
              <template #default="scope">
                <span v-if="scope.row.dailyMissionExecutionCount">{{ scope.row.dailyMissionExecutionCount }} 次</span>
                <span v-else> -- </span>
              </template>
            </el-table-column>
            <el-table-column prop="description" label="注意事项" />
            <el-table-column fixed="right" label="操作" width="190" align="center">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  :icon="Edit"
                  size="small"
                  @click="openDrawer('编辑', scope.row.categorizeId, scope.row)"
                  v-if="value === '查看自建任务'"
                  v-auth="'mission_index_save'"
                >
                  编辑
                </el-button>
                <el-button
                  link
                  type="danger"
                  :icon="Delete"
                  size="small"
                  v-if="value === '查看自建任务'"
                  @click="deleteMission(scope.row)"
                  v-auth="'mission_index_delete'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 照护项目抽屉组件 -->
    <CareMissionDrawer ref="drawerRef" />
  </div>
</template>
<script setup lang="ts">
import {
  getCareMissionCategorizeList,
  saveCareMissionCategorize,
  deleteCareMissionCategorize,
  sortCareMissionCategorize
} from "@/api/modules/care-mission-categorize";
import { deleteCareMission } from "@/api/modules/care-mission";
import { CareMission } from "@/api/interface";
import { onMounted, ref } from "vue";
import { Plus, Edit, Delete, Sort } from "@element-plus/icons-vue";
import { ElMessageBox, ElMessage } from "element-plus";
import CareMissionDrawer from "./components/CareMissionDrawer.vue";
// import { useUserStore } from "@/stores/modules/user";

const value = ref("查看平台推荐任务");
const options = ["查看平台推荐任务", "查看自建任务"];
// 护理项目分类列表
const careMissionCategorizeList = ref<CareMission.ResCareMissionCategorize[]>([]);

// 加载护理项目分类列表
onMounted(async () => {
  await loadCareMissionCategorizeList();
});

// 加载护理项目分类列表
const loadCareMissionCategorizeList = async () => {
  const params: CareMission.ReqCareMissionCategorizeListParams = {
    includeMissions: true,
    selectPlatform: value.value === "查看平台推荐任务"
  };
  const res = await getCareMissionCategorizeList(params);
  careMissionCategorizeList.value = res.data;
};

// 添加任务分类
const addCategorize = () => {
  ElMessageBox.prompt("", "添加任务分类", {
    confirmButtonText: "保存",
    cancelButtonText: "关闭",
    inputPlaceholder: " 请输入任务分类名称",
    inputValidator: (value: string) => {
      if (!value) {
        return "请输入任务分类名称";
      }
      return true;
    }
  }).then(async ({ value }) => {
    const data: CareMission.ReqCareMissionCategorizeSaveParams = {
      name: value,
      sort: 0
    };
    await saveCareMissionCategorize(data);
    await loadCareMissionCategorizeList();
    ElMessage({
      message: "保存成功",
      type: "success"
    });
  });
};

// 编辑任务分类名称
const editCategorizeName = (mc: CareMission.ResCareMissionCategorize) => {
  ElMessageBox.prompt("", "编辑任务分类名称", {
    confirmButtonText: "保存",
    cancelButtonText: "关闭",
    inputPlaceholder: " 请输入任务分类名称",
    inputValue: mc.name,
    inputValidator: (value: string) => {
      if (!value) {
        return "请输入任务分类名称";
      }
      return true;
    }
  }).then(async ({ value }) => {
    const data: CareMission.ReqCareMissionCategorizeSaveParams = {
      id: mc.id,
      name: value,
      sort: mc.sort
    };
    await saveCareMissionCategorize(data);
    mc.name = value;
    ElMessage({
      message: "保存成功",
      type: "success"
    });
  });
};

// 删除任务分类
const deleteCategorize = (mc: CareMission.ResCareMissionCategorize) => {
  ElMessageBox.confirm("", "确认删除任务分类吗？", {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    await deleteCareMissionCategorize(mc.id);
    await loadCareMissionCategorizeList();
    ElMessage({
      message: "删除成功",
      type: "success"
    });
  });
};

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof CareMissionDrawer> | null>(null);
const openDrawer = (title: string, categorizeId: number = 0, row: Partial<CareMission.ResCareMission> = {}) => {
  row.categorizeId = categorizeId;
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    getTableList: () => loadCareMissionCategorizeList()
  };
  drawerRef.value?.acceptParams(params);
};
// 删除照护项目
const deleteMission = (mission: CareMission.ResCareMission) => {
  ElMessageBox.confirm("", `确认删除照护项目「${mission.name}」吗？`, {
    confirmButtonText: "删除",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      await deleteCareMission(mission.id);
      await loadCareMissionCategorizeList();
      ElMessage({
        message: "删除成功",
        type: "success"
      });
    } catch (error) {
      console.error("删除照护项目失败", error);
      ElMessage.error("删除失败");
    }
  });
};

// 设置任务分类排序
const setCategorizeSort = (mc: CareMission.ResCareMissionCategorize) => {
  ElMessageBox.prompt("提示：分类排序值越小，排序越靠前", "设置任务分类排序", {
    confirmButtonText: "保存",
    cancelButtonText: "关闭",
    inputPlaceholder: "请输入任务分类排序, 值越小，排序越靠前",
    inputValue: mc.sort + "",
    inputType: "number",
    inputValidator: value => {
      if (!value) {
        return "请输入任务分类排序, 值越小，排序越靠前";
      }
      return true;
    }
  }).then(async ({ value }) => {
    const data: CareMission.ReqCareMissionCategorizeSortParams = {
      id: mc.id,
      sort: Number(value)
    };
    await sortCareMissionCategorize(data);
    mc.sort = Number(value);
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    await loadCareMissionCategorizeList();
  });
};
</script>

<style scoped lang="scss">
.categorize-container {
  width: 100%;
}
.categorize-title {
  padding: 12px;
  font-size: 16px;
  font-weight: bold;
  background-color: var(--el-color-primary-light-9);
}
.top-box {
  padding: 10px;
  margin-bottom: 15px;
  border: 1px solid var(--el-aside-border-color);
  border-radius: 4px;
}
.categorize-box {
  margin-bottom: 15px;
  overflow: hidden;
  border: 1px solid var(--el-aside-border-color);
  border-radius: 4px;
}
</style>
